package vip.xumy.core.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import lombok.extern.log4j.Log4j2;
import vip.xumy.core.exception.CoreException;
import vip.xumy.core.golbal.GlobalConstant;

/**
 * Ownership belongs to the company author:mengyxu date:2021年1月20日
 */

@Log4j2
public class ShellUtil {
	public static final boolean IS_LINUX;
	
	static {
		IS_LINUX = "linux".equals(System.getProperty("os.name").toLowerCase());
	}

	public static int executeShellCmd(String cmd) throws CoreException {
		try {
			log.info("ShellUtil runtime exec commond----------------->" + cmd);
			Process process = null;
			if(IS_LINUX) {
				process = Runtime.getRuntime().exec(new String[] {"/bin/sh", "-c", cmd});
			}else {
				process = Runtime.getRuntime().exec(cmd);
			}

			if (process != null) {
				final InputStream input = process.getInputStream();
				logInputStream(cmd, input);

				process.waitFor();
				log.info("process result:" + process.exitValue());// 0代表成功，其他代表失败，返回未终止的子进程的数量
				process.destroy();
				return process.exitValue();
			}
		} catch (Exception e) {
			log.error("Execute shell error log", e);
			return -1;
		}
		// end
		return 0;
	}

	/**
	 * In order to log input stream
	 * 
	 * @param in
	 * @throws UnsupportedEncodingException
	 */
	public static void logInputStream(String shells, InputStream in) throws UnsupportedEncodingException {

		StringBuilder builder = new StringBuilder();
		builder.append("Shell [").append(shells).append(" return log: ");
		String str = null;
		try (final BufferedReader inBr = new BufferedReader(new InputStreamReader(in, GlobalConstant.ENCODING_UTF8));) {
			while ((str = inBr.readLine()) != null) {
				builder.append(str);
				builder.append("\n");
			}
		} catch (IOException e) {
			log.error("Read log inputstream failed!", e);
		}

		// Log to file.
		log.info(builder.toString());
	}

	private ShellUtil() {
		// Not allow to create instance.
	}

}
